<?php

namespace app\common\controller;

use think\Controller;

class Home extends Controller
{
    //不需要登录的方法
    protected $NoNeedLogin = [];

    //用户模型
    protected $BusinessModel = null;

    //用户信息
    protected $auth = null;

    public function __construct()
    {
        parent::__construct();

        $this->BusinessModel = model('business.Business');

        // 获取方法名
        $action = $this->request->action();

        if (!in_array($action, $this->NoNeedLogin) && !in_array('*', $this->NoNeedLogin)) {
            $this->IsLogin();
        }
    }

    /**
     * 验证登录
     * @param bool $redirect 重定向参数 true为默认跳转 false为不跳转
     * @param string $url 返回指定页面
     * @return array 如果 redirect 为 false的时候， 就返回登录信息
     */
    protected function IsLogin($redirect = true, $url = null)
    {
        $business = cookie('business') ?? '';

        // 获取当前域名
        $domain = $this->request->domain();

        $redirectUrl = rtrim($this->request->server('HTTP_REFERER'), '/');

        $redirectUrl = $domain === $redirectUrl ? null : $this->request->server('HTTP_REFERER');

        $url = empty($url) ? $redirectUrl : $url;

        cookie('redirect', $url);

        if (empty($business)) {
            if ($redirect === true) {
                $this->error('请登录', url('/home/index/login'));
            }
        }

        $id = $business['id'] ?? 0;
        $mobile = $business['mobile'] ?? '';

        // 组装条件数组 `id` = '$id' AND `mobile` = '$mobile'
        $where = [
            'id' => $id,
            'mobile' => $mobile
        ];

        // 查询数据表是否有该id和该手机号
        $auth = $this->BusinessModel->where($where)->find();

        if (empty($auth)) {
            cookie('business', null);

            if ($redirect) {
                $this->error('非法登录', url('/home/index/login'));
            } else {
                return null;
            }
        }

        // 模板赋值 (['模板变量名' => '数据变量名'])
        $this->view->assign(['auth' => $auth]);

        // 给继承这个公共控制器的子控制器赋值一个用户信息属性
        $this->auth = $auth;

        return $auth;
    }
}
